#include "userlist.h"
#include <time.h>
#include<stdlib.h>

UserList::UserList()
{
	sp_thread_mutex_init( &mMutex, NULL );
}

UserList :: ~UserList()
{
	sp_thread_mutex_destroy( &mMutex );
}

void UserList :: copy( SP_SidList * outList, SP_Sid_t * ignoreSid )
{
	sp_thread_mutex_lock( &mMutex );

	for( int i = 0; i < mList.getCount(); i++ ) {
		if( NULL != ignoreSid ) {
			SP_Sid_t theSid = mList.get( i );
			if( theSid.mKey == ignoreSid->mKey && theSid.mSeq == ignoreSid->mSeq ) {
				continue;
			}
		}

		outList->add( mList.get( i ) );
	}

	sp_thread_mutex_unlock( &mMutex );
}

void UserList :: remove( SP_Sid_t sid )
{
	sp_thread_mutex_lock( &mMutex );

	for( int i = 0; i < mList.getCount(); i++ ) {
		SP_Sid_t theSid = mList.get( i );
		if( theSid.mKey == sid.mKey && theSid.mSeq == sid.mSeq ) {
			mList.take( i );
			break;
		}
	}

	sp_thread_mutex_unlock( &mMutex );
}

void UserList :: add( SP_Sid_t sid )
{
	sp_thread_mutex_lock( &mMutex );

	mList.add( sid );

	sp_thread_mutex_unlock( &mMutex );
}

int UserList :: getCount()
{
	int count = 0;

	sp_thread_mutex_lock( &mMutex );

	count = mList.getCount();

	sp_thread_mutex_unlock( &mMutex );

	return count;
}
SP_Sid_t UserList :: getRandUser()
{
	SP_Sid_t sid;
	srand(time(NULL));
	sp_thread_mutex_lock( &mMutex );
	if(getCount()>0)
	{
	    int index=rand() % getCount();
		sid=mList.get(index);
	}
	sp_thread_mutex_unlock( &mMutex );
	return sid;
}